package com.filter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.client.cache.LimitCapacityManager;
import com.manage.model.SyncConfig;
import com.manage.service.SyncConfigService;
import com.manage.service.SyncConfigServiceImpl;
import com.util.Singleton;
import com.util.Util;

public class SystemLimitFilter extends Singleton {
	public static SystemLimitFilter getInstance()
	{
		return (SystemLimitFilter)SystemLimitFilter.getInstance(SystemLimitFilter.class.getName());
	}
	public SystemLimitFilter()
	{
		 service = new SyncConfigServiceImpl();
		SystemLimitFilterThread it = new SystemLimitFilterThread();
		it.start();
		init();
	} 
	
	class SystemLimitFilterThread extends Thread
	{
		@Override
		public void run() {
			while(true)
			{
				SystemLimitFilter.getInstance().init();
				try {
					sleep(5*60*1000);
				} catch (InterruptedException e) {
				}
			}
		}
	}
	private void init()
	{
		list = service.getSyncConfigs();
	}
	SyncConfigService service;
	private Logger logger = Logger.getLogger(this.getClass());
	
	private List<SyncConfig> list = new ArrayList<SyncConfig>();
	/**
	 * mobile 手机号码
	 * @return true 过滤 false 不过滤
	 */
	public boolean isSystemLimit(String mobile,String imsi,String imei,String extchid,String productid)
	{
		float dayLimit = 1000;
		float monthLimit = 2000;
		if(extchid!=null && Integer.parseInt(extchid)!=0 && productid!=null && Integer.parseInt(productid)!=0)
		{
			if(extchid!=null && !extchid.equals(""))
			{
				for(int i =0 ;i<list.size();i++)
				{
					SyncConfig syn = list.get(i);
					if(Integer.parseInt(extchid)==syn.getChannelid())
					{
						dayLimit = syn.getPaydaylimit();
						monthLimit = syn.getPaymonthlimit();
					}
				}
			}
			Map<String, String> userLimit = LimitCapacityManager.getInstance().getUserLimit(mobile+imsi);
			if(monthLimit>0)
			{
				if((Float.parseFloat(userLimit.get("monthnum")))>=monthLimit)
				{
					logger.error(Util.dateToString(new Date())+" mobile imsi " + mobile+" "+imsi+" is SystemLimitFilter monthnum");
					return true;
				}
			}
			if(dayLimit>0)
			{
				if((Float.parseFloat(userLimit.get("daynum")))>=dayLimit)
				{
					logger.error(Util.dateToString(new Date())+" mobile imsi " + mobile+" "+imsi+" is SystemLimitFilter daynum");
					return true;
				}
			}
		}
		return false;
	}
}
